from django.contrib.auth.hashers import make_password
from django.shortcuts import render, HttpResponse, redirect, reverse
from App.models import *
from django.db import IntegrityError
from django.contrib.auth import logout as auth_logout


# Create your views here.

# 首页
def index(request):
    # 从 Cookie 获取用户ID
    user_id = request.COOKIES.get('user_id', None)

    # 获取登录的用户
    user = None
    if user_id:
        user = UserModel.objects.filter(id=user_id).first()
        print('-' * 60)
        print(user)

    return render(request, 'index.html', {'user': user})


# 登录
def login(request):
    if request.method == "GET":
        return render(request, 'index.html')
    elif request.method == "POST":
        uname = request.POST.get('uname')
        passwd = request.POST.get('passwd')

        users = UserModel.objects.filter(name=uname, password=passwd)
        if users.exists():
            user = users.first()
            response = redirect(reverse('index'))
            response.set_cookie('user_id', user.id, max_age=3600)  # 保持使用 user_id
            return response
        else:
            return render(request, 'index.html', {'error': '用户名或密码错误'})


# 注册
def register(request):
    if request.method == "GET":
        return render(request, 'register.html')
    elif request.method == "POST":
        # 如果是 POST 请求，处理表单数据
        uname = request.POST.get('uname')
        passwd = request.POST.get('passwd')
        age = request.POST.get('age')

        # 表单验证
        if not uname or not passwd or not age:
            return render(request, 'register.html', {'error': '用户名、密码和年龄不能为空'})

        # 检查用户名是否已被注册
        if UserModel.objects.filter(name=uname).exists():
            return render(request, 'register.html', {'error': '该用户名已被注册'})

        # 创建用户
        try:
            user = UserModel(
                name=uname,
                password=make_password(passwd),  # 使用 Django 的密码加密机制
                age=age
            )
            user.save()
            return redirect(reverse('login'))  # 注册成功后跳转到登录页面
        except IntegrityError as e:
            return HttpResponse(f"注册失败：{e}")


# 注销
def logout(request):
    response = redirect(reverse('index'))
    response.delete_cookie('user_id')  # 清除 user_id Cookie
    return response
